package com.jesper.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jesper.model.Item;
import com.jesper.model.ItemCategory;
import com.jesper.model.ReItem;
import com.jesper.model.ResObject;
import com.jesper.service.ItemCategoryService;
import com.jesper.service.ItemService;
import com.jesper.service.ReItemService;
import com.jesper.util.Constant;
import com.jesper.util.DateUtil;
import com.jesper.util.PageUtil;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import com.pig4cloud.plugin.excel.annotation.Sheet;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Random;


/**
 * 商品管理
 */
@Controller
@Slf4j
public class ItemController {


    @Autowired
    ItemService itemService;

    List<Item> itemList;
    File getFile = null;
    String imageName = null;
    @Autowired
    MinioClient minioClient;
    @Autowired
    private FileStorageService fileStorageService;//注入实列
    @Autowired
    private ItemCategoryService itemCategoryService;
    @Autowired
    private ReItemService reItemService;

    //商品分页
    @PreAuthorize("hasAuthority('admin')")
    @RequestMapping("/user/itemManage_{pageCurrent}_{pageSize}_{pageCount}")
    public String itemManage(Item item, @PathVariable Integer pageCurrent,
                             @PathVariable Integer pageSize,
                             @PathVariable Integer pageCount,
                             Model model) {
        if (pageSize == 0) pageSize = 50;
        if (pageCurrent == 0) pageCurrent = 1;


        Page<Item> itemPage = itemService.query(pageCurrent, pageSize, item);


        int rows = new Long(itemPage.getTotal()).intValue();

        if (pageCount == 0) pageCount = rows % pageSize == 0 ? (rows / pageSize) : (rows / pageSize) + 1;
        item.setStart((pageCurrent - 1) * pageSize);
        item.setEnd(pageSize);
        itemList = itemPage.getRecords();
        for (Item i : itemList) {
            i.setUpdatedStr(DateUtil.getDateStr(i.getUpdated()));
        }
        ItemCategory itemCategory = new ItemCategory();
        itemCategory.setStart(0);
        itemCategory.setEnd(Integer.MAX_VALUE);
        List<ItemCategory> itemCategoryList = itemCategoryService.list1();
        Integer minPrice = item.getMinPrice();
        Integer maxPrice = item.getMaxPrice();
        model.addAttribute("itemCategoryList", itemCategoryList);
        model.addAttribute("itemList", itemList);
        String pageHTML = PageUtil.getPageContent("itemManage_{pageCurrent}_{pageSize}_{pageCount}?title=" + item.getTitle() + "&cid=" + item.getCid() + "&minPrice" + minPrice + "&maxPrice" + maxPrice, pageCurrent, pageSize, pageCount);
        model.addAttribute("pageHTML", pageHTML);
        model.addAttribute("item", item);
        return "item/itemManage";
    }

    //商品信息导出
    @RequestMapping("/user/download1")
    @ResponseExcel(name = "商品列表", sheets = @Sheet(sheetName = "现有商品"))
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    public List<Item> excel() {
        List<Item> list = itemService.itemList();
        return list;
    }

    //商品编辑界面
    @GetMapping("/user/itemEdit")
    public String itemEditGet(Model model, Item item) {
        ItemCategory itemCategory = new ItemCategory();
        itemCategory.setStart(0);
        itemCategory.setEnd(Integer.MAX_VALUE);
        List<ItemCategory> itemCategoryList = itemCategoryService.list1();
        model.addAttribute("itemCategoryList", itemCategoryList);
        if (item.getId() != null) {
            Item item1 = itemService.getById(item.getId());

            String id = String.valueOf(item.getId());

//            GridFSDBFile fileById = mongoUtil.getFileById(id);
//            if (fileById != null) {
//                StringBuilder sb = new StringBuilder(ROOT);
//                imageName = fileById.getFilename();
//                sb.append(imageName);
//                try {
//                    getFile = new File(sb.toString());
//                    fileById.writeTo(getFile);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                item1.setImage(imageName);
//            }
            model.addAttribute("item", item1);
        }
        return "item/itemEdit";
    }

    @PostMapping("/user/itemEdit")
    public String itemEditPost(Model model, HttpServletRequest request, @RequestParam("file") MultipartFile file, Item item, HttpSession httpSession) {
        //根据时间和随机数生成id
        Date date = new Date();
        item.setCreated(date);
        item.setUpdated(date);
        item.setBarcode("");
        item.setImage("");


        Long id = item.getId();

        if (id == null) {

        } else {
            Random random = new Random();
            id = (long) ((random.nextDouble() * (99999 - 10000 + 1)) + 1000);
        }

        if (file.isEmpty()) {
            System.out.println("图片未上传");
        } else {


            FileInfo fileInfo = fileStorageService.of(file)
                    .setPath(id + "/") //保存到相对路径下，为了方便管理，不需要可以不写
                    .setObjectId(id)   //关联对象id，为了方便管理，不需要可以不写
                    .setSaveFilename(file.getOriginalFilename())
                    .upload();  //将文件上传到对应地方

            item.setImage(fileInfo.getBasePath() + fileInfo.getPath() + fileInfo.getOriginalFilename());
        }

        if (id != null) {
            itemService.updateById(item);
        } else {
            item.setId(id);
            itemService.save(item);
        }
        return "redirect:itemManage_0_0_0";
    }

    @GetMapping(value = "/{filename:.+}")
    @ResponseBody
    public ResponseEntity<?> getFile() {
//        try {
//            return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(ROOT, imageName)));
//        } catch (Exception e) {
//
//        }
        return ResponseEntity.notFound().build();
    }

    @ResponseBody
    @PostMapping("/user/itemEditState")//商品状态编辑
    public ResObject<Object> itemEditState(Item item1) {
        Item item = itemService.getById(item1.getId());//通过MP的方法拿到item对象的基本参数，然后逐个set进reItem对象
        ReItem reItem = new ReItem();//创建reItem对象
        reItem.setId(item.getId());
        reItem.setBarcode(item.getBarcode());
        reItem.setCid(item.getCid());
        reItem.setImage(item.getImage());
        reItem.setPrice(item.getPrice());
        reItem.setNum(item.getNum());
        reItem.setSellPoint(item.getSellPoint());
        reItem.setStatus(item.getStatus());
        reItem.setTitle(item.getTitle());
        reItem.setRecovered(new Date());
        reItemService.save(reItem);//调用reItem方法的新增方法
        itemService.removeById(item1.getId());
        ResObject<Object> object = new ResObject<Object>(Constant.Code01, Constant.Msg01, null, null);
        return object;
    }

    @GetMapping("/user/selectImage/{id}")
    public ResponseEntity<byte[]> getImage(@PathVariable Long id, @Value("${spring.minio.bucket-name}") String bucketName) {
        InputStream objectResponse = null;
        try {
            Item obj = itemService.getById(id);
            String image = obj.getImage();
            objectResponse = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(image).build());

            byte[] allBytes = org.apache.commons.io.IOUtils.toByteArray(objectResponse);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_JPEG);
            return new ResponseEntity<>(allBytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        } finally {
            org.apache.commons.io.IOUtils.closeQuietly(objectResponse);
        }
    }
}
